from rest_framework import serializers
from .models import UserInfo
from .models import UserLog
from .models import OperationLog

class UserSerializer(serializers.ModelSerializer):
    # 如果你需要包含密码字段，确保它是只写的,更新数据不填密码，创建需要密码
    password = serializers.CharField(write_only=True, required=False)

    last_login = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    date_joined = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)

    class Meta:
        model = UserInfo
        fields = "__all__"
        read_only_fields = ("id",)

    #重写使密码加密存储
    def create(self, validated_data):
        # 弹出密码字段，因为我们稍后会用set_password来处理它
        password = validated_data.pop('password')
        # 创建用户实例，但不设置密码
        user = UserInfo.objects.create(**validated_data)
        # 使用set_password来加密密码
        user.set_password(password)
        # 保存用户实例
        user.save()
        return user

    # def update(self, instance, validated_data):
        # 密码加密 及 is_active保存为数字
        # password = validated_data.pop('password')
        # instance.set_password(password)
        # instance.is_active = validated_data.get('is_active')
        # instance.save()
        # return instance


class UserLogSerializer(serializers.ModelSerializer):
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    class Meta:
        model = UserLog
        fields = "__all__"
        read_only_fields = ('id',)


class OperatelogSerializer(serializers.ModelSerializer):
    timestamp = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    class Meta:
        model = OperationLog
        fields = "__all__"
        read_only_fields = ('id',)



